package com.baosight.risk.web.quartz;

import com.baosight.risk.api.quartz.ISysJobService;
import com.baosight.risk.base.controller.BaseController;
import com.baosight.risk.common.annotation.Log;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.enums.BusinessType;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.common.utils.ExcelUtil;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.service.quartz.entity.SysJob;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.List;


/**
 * @author duanyongqiang
 * <p>
 * 定时任务管理
 */
@Slf4j
@RestController
@RequestMapping("system/job")
@Api(value = "定时任务", description = "定时任务管理", produces = MediaType.APPLICATION_JSON)
public class SysJobController extends BaseController {


    @Autowired
    private ISysJobService jobService;

    /**
     * 返回集合列表
     */
    @RequiresPermissions("system:job:list")
    @GetMapping("/list")
    @ApiOperation("查询定时任务数据")
    public AjaxResult query(SysJob job) {
        startPage("row_order", "asc");
        List<SysJob> jobs = jobService.selectJob(job);
        if(BeanUtils.sortList(jobs)) {
            for (SysJob sysJob : jobs) {
                SysJob param = new SysJob();
                param.setId(sysJob.getId());
                param.setRowOrder(sysJob.getRowOrder());
                jobService.updateJobParam(sysJob);
            }

        }
        return getResultPage(jobs);
    }

    /**
     * 任务调度状态修改
     */
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    @ApiOperation("任务调度状态修改")
    public AjaxResult changeStatus(@RequestParam("id") String id,
                                   @RequestParam("status") String status) {
        SysJob job = (SysJob) BeanUtils.updateBean(jobService.get(id));
        job.setStatus(status);
        return toAjax(jobService.changeStatus(job));
    }

    /**
     * 任务调度立即执行一次
     */
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/run")
    @ApiOperation("任务调度立即执行一次")
    public AjaxResult get(@RequestParam("id") String id, @RequestParam("acctYear") String acctYear, @RequestParam("quarterCode") String quarterCode,
                          @RequestParam("manageCompCode") String manageCompCode, @RequestParam("manageCompName") String manageCompName) {
        SysJob sysJob = new SysJob();
        String year = StringUtils.isNotEmpty(acctYear) ? acctYear : " ";
        String quarter = StringUtils.isNotEmpty(quarterCode) ? quarterCode : " ";
        String manageCode = StringUtils.isNotEmpty(manageCompCode) ? manageCompCode : " ";
        String manageName = StringUtils.isNotEmpty(manageCompName) ? manageCompName : " ";
        sysJob.setId(id);
        sysJob.setMethodParams(year + "," + quarter + "," + manageCode + "," + manageName+","+id);
        if (jobService.updateJobParam(sysJob) > 0) {
            SysJob job = jobService.get(id);
            return toAjax(jobService.run(job));
        }
        return AjaxResult.error();
    }

    @PostMapping("/save")
    @ApiOperation("保存定时任务")
    public AjaxResult save(@RequestBody SysJob job) {
        job = (SysJob) BeanUtils.initBean(job);
        job.setMisfirePolicy("2");
        job.setStatus("1");
        return toAjax(jobService.insertJobCron(job));
    }

    /**
     * 修改调度
     */
    @GetMapping("/edit")
    @ApiOperation("修改调度")
    public AjaxResult edit(@RequestParam("id") String id) {
        return success(jobService.get(id));
    }

    /**
     * 修改保存调度
     */
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ApiOperation("修改保存调度")
    public AjaxResult editSave(@RequestBody SysJob job) {
        job = (SysJob) BeanUtils.updateBean(job);
        SysJob j = jobService.get(job.getId());
        job.setMisfirePolicy(j.getMisfirePolicy());
        job.setStatus(j.getStatus());
        return toAjax(jobService.updateJobCron(job));
    }

    /**
     * 校验cron表达式是否有效
     */
    @PostMapping("/checkCronExpressionIsValid")
    @ApiOperation("校验cron表达式是否有效")
    public AjaxResult checkCronExpressionIsValid(@RequestParam("cronExpression") String cronExpression) {

        boolean b = jobService.checkCronExpressionIsValid(cronExpression);
        if (b) {
            return success();
        } else {
            return error("cron表达式错误");
        }
    }


    @Log(title = "定时任务", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ApiOperation("删除定时任务")
    public AjaxResult remove(@RequestBody List<String> ids) {
        jobService.deleteJobByIds(ids);
        return success();
    }


    /**
     * 导出excel
     *
     * @return
     */
    @PostMapping("export")
    @ResponseBody
    @ApiOperation("导出定时任务数据")
    public AjaxResult exportExcel(List<String> columNameList) {
        ExcelUtil<SysJob> excel = new ExcelUtil<>(SysJob.class);
        return excel.exportExcel(jobService.selectAll(), "定时任务", columNameList);
    }

    /**
     * 修改排序
     */
    @GetMapping("/order")
    @ApiOperation("修改排序")
    public AjaxResult rowOrder(SysJob job) {
        SysJob param = new SysJob();
        param.setId(job.getId());
        param.setRowOrder(job.getRowOrder());
        jobService.updateJobParam(param);
        return AjaxResult.success();
    }

}
